﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CoilIntelStorage.Models;
using CoilIntelStorage.Utils;
using CoilIntelStorage.ViewModels;

namespace CoilIntelStorage
{
    /// <summary>
    /// StockIn.xaml 的交互逻辑
    /// </summary>
    public partial class StockIn : Window
    {
        public delegate void sendMessage(string message);//创建带参数委托
        public event sendMessage Send;

        public StockIn()
        {
            InitializeComponent();
            //StockInViewModel viewModel = new StockInViewModel();
            ////修改设置MainPage对象的DataContext属性的语句，来引用新的ViewModel对象。
            //this.DataContext = viewModel;
            LoadWorkableStockList();
        }
        /// <summary>
        /// 加载可用的空位置列表
        /// </summary>
        private void LoadWorkableStockList()
        {
            //加载库位列表
            DataTable dataTable = DbHelper.GetTable("SELECT * FROM stock WHERE status = 0");
            List<Stock> PositionViewModels = new List<Stock>();
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                Stock stock = new Stock();
                DataRow dataRow = dataTable.Rows[i];
                stock.Id = Convert.ToInt32(dataRow["id"]);
                stock.Name = dataRow["name"].ToString();
                stock.Status = Convert.ToInt32(dataRow["status"]);
                stock.Lock_status = Convert.ToInt32(dataRow["lock_status"]);
                stock.Lock_type = Convert.ToInt32(dataRow["lock_Type"]);
                PositionViewModels.Add(stock);
            }
            this.cbx_position.ItemsSource = PositionViewModels;
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Send("Refresh command list");
            this.rb_entrance1.IsChecked = true;
            this.rb_entrance2.IsChecked = false;
            this.cbx_position.SelectedItem = null;
            this.txt_name.Text = "";
            this.txt_order_no.Text = "";
            this.txt_info.Text = "";
            this.Hide();
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void save_Click(object sender, RoutedEventArgs e)
        {
            if (this.cbx_position.SelectedItem == null)
            {
                MessageBox.Show("请选择摆放库位。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else if (this.txt_name.Text.Length == 0)
            {
                MessageBox.Show("请输入物料名称。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else if (this.txt_order_no.Text.Length == 0)
            {
                MessageBox.Show("请输入订单编号。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else if (this.txt_info.Text.Length == 0)
            {
                MessageBox.Show("请输入货物信息。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else
            {
                try
                {
                    DateTime date = DateTime.Now;
                    string specificDate = date.ToString("yyyy") + date.ToString("MM") + date.ToString("dd");
                    Goods goods = new Goods();
                    goods.Name = this.txt_name.Text;
                    goods.Code = GetSerialNumber(specificDate);
                    goods.Amount = 1;
                    goods.Order_no = this.txt_order_no.Text;
                    goods.Info = this.txt_info.Text;
                    goods.Stock_name = (this.cbx_position.SelectedItem as Stock).Name;
                    String sql = "INSERT INTO goods(name,code,amount,order_no,info,stock_name)VALUES(@name,@code,@amount,@order_no,@info,@stock_name);";
                    SqlParameter[] sqlParameters = new SqlParameter[] {
                    new SqlParameter("@name",goods.Name),
                    new SqlParameter("@code",goods.Code),
                    new SqlParameter("@amount",goods.Amount),
                    new SqlParameter("@order_no",goods.Order_no),
                    new SqlParameter("@info",goods.Info),
                    new SqlParameter("@stock_name",goods.Stock_name)};
                    int n = DbHelper.ExcuteSQL(sql, sqlParameters);
                    TaskQueue taskQueue = new TaskQueue();
                    taskQueue.Type = 1;
                    if (this.rb_entrance1.IsChecked == true)
                    {
                        taskQueue.Start_point = "1#";
                    }
                    if (this.rb_entrance2.IsChecked == true)
                    {
                        taskQueue.Start_point = "2#";
                    }
                    taskQueue.End_point = (this.cbx_position.SelectedItem as Stock).Name;
                    taskQueue.Build_time = date;
                    taskQueue.Status = 1;
                    taskQueue.Goods_code = goods.Code;
                    string sql2 = "INSERT INTO task_queue(type,start_point,end_point,build_time,status,goods_code)VALUES(@type,@start_point,@end_point,@build_time,@status,@goods_code);";
                    SqlParameter[] sqlParameters2 = new SqlParameter[] {
                    new SqlParameter("@type",taskQueue.Type),
                    new SqlParameter("@start_point",taskQueue.Start_point),
                    new SqlParameter("@end_point",taskQueue.End_point),
                    new SqlParameter("@build_time",taskQueue.Build_time),
                    new SqlParameter("@status",taskQueue.Status),
                    new SqlParameter("@goods_code",taskQueue.Goods_code)};
                    n += DbHelper.ExcuteSQL(sql2, sqlParameters2);

                    Instruction instruction = new Instruction();
                    instruction.Start_point = 1;
                    instruction.End_point = 1;
                    instruction.Send_time = date;
                    ElectronicMessage inStockElectronicMessage = new ElectronicMessage();
                    inStockElectronicMessage.Type = 1;
                    inStockElectronicMessage.Instructions = "入库请求";
                    if (taskQueue.Start_point.Equals("1#"))
                    {
                        inStockElectronicMessage.EntranceAndExit = 1;
                    }
                    else if (taskQueue.Start_point.Equals("2#"))
                    {
                        inStockElectronicMessage.EntranceAndExit = 2;
                    }
                    inStockElectronicMessage.Head = 101;
                    inStockElectronicMessage.Code = taskQueue.Goods_code.Replace("-", "");
                    inStockElectronicMessage.SendOrAnswer = "01";
                    instruction.Socket_code = inStockElectronicMessage.Head.ToString() +
                        inStockElectronicMessage.EntranceAndExit.ToString() +
                        goods.Stock_name.Replace("-", "") +
                        inStockElectronicMessage.Code +
                        inStockElectronicMessage.SendOrAnswer;
                    instruction.Content = inStockElectronicMessage.Instructions;
                    DataSet ds = DbHelper.GetDataSet("SELECT MAX(id) as id FROM task_queue");
                    instruction.Task_id = Convert.ToInt32(ds.Tables[0].Rows[0]["id"]);
                    string sql3 = "INSERT INTO instruction(start_point,end_point,send_time,socket_code,content,task_id)VALUES(@start_point,@end_point,@send_time,@socket_code,@content,@task_id);";
                    SqlParameter[] sqlParameters3 = new SqlParameter[] {
                    new SqlParameter("@start_point",instruction.Start_point),
                    new SqlParameter("@end_point",instruction.End_point),
                    new SqlParameter("@send_time",instruction.Send_time),
                    new SqlParameter("@socket_code",instruction.Socket_code),
                    new SqlParameter("@content",instruction.Content),
                    new SqlParameter("@task_id",instruction.Task_id)};
                    n += DbHelper.ExcuteSQL(sql3, sqlParameters3);
                    if (n == 3)
                    {
                        MessageBox.Show("创建新任务成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                        Send("Refresh command list");
                        this.rb_entrance1.IsChecked = true;
                        this.rb_entrance2.IsChecked = false;
                        this.cbx_position.SelectedItem = null;
                        this.txt_name.Text = "";
                        this.txt_order_no.Text = "";
                        this.txt_info.Text = "";
                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show("创建新任务失败！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 获取流水号
        /// </summary>
        /// <returns>流水号</returns>
        private string GetSerialNumber(String specificDate)
        {
            string result = null;
            DataSet dataSet = DbHelper.GetDataSet("SELECT TOP 1 code FROM goods WHERE substring(code,0,CHARINDEX('-',code)) = '" + specificDate + "' ORDER BY code DESC");
            if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
            {
                result = dataSet.Tables[0].Rows[0]["code"].ToString();
            }
            if (result == null)
            {
                result = specificDate + "-001";
            }
            else
            {
                int lastSerialNumber = Convert.ToInt32(result.Substring(result.IndexOf("-") + 1));
                int newSerialNumber = lastSerialNumber + 1;
                result = specificDate + "-" + newSerialNumber.ToString("000");
            }
            return result;
        }



        
    }
}
